/*
 * Copyright 2016 Zhongan.com All right reserved. This software is the
 * confidential and proprietary information of Zhongan.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Zhongan.com.
 */
package com.liuyfly.commons;

import java.lang.reflect.Field;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

import lombok.extern.slf4j.Slf4j;

/**
 * 类SuperclassExclusionStrategy.java的实现描述：JSON解析策略
 * 
 * @author AngleSuper.Wei
 */
@Slf4j
public class SuperclassExclusionStrategy implements ExclusionStrategy {

    /**
     * 是否跳过类
     */
    @Override
    public boolean shouldSkipClass(Class<?> arg0) {
        return false;
    }

    /**
     * 是否跳过属性
     */
    @Override
    public boolean shouldSkipField(FieldAttributes fieldAttributes) {
        String fieldName = fieldAttributes.getName();
        Class<?> theClass = fieldAttributes.getDeclaringClass();

        return isFieldInSuperclass(theClass, fieldName);
    }

    private boolean isFieldInSuperclass(Class<?> subclass, String fieldName) {
        Class<?> superclass = subclass.getSuperclass();
        Field field;

        while (superclass != null) {
            field = getField(superclass, fieldName);

            if (field != null)
                return true;

            superclass = superclass.getSuperclass();
        }

        return false;
    }

    private Field getField(Class<?> theClass, String fieldName) {
        try {
            return theClass.getDeclaredField(fieldName);
        } catch (Exception e) {
            // 不是失败，不要记ERROR log
            log.debug("Get field exception={}", e);
            return null;
        }
    }
}
